#include "task/Ls/Ls.h"
#include "string.h"
#include "ConfigReader.h"
#include "FileUtils.h"
#include <iostream>
#include "SocketIO.h"
namespace task {
    int Ls::clientAction(socketinf serverinf, const char * arg, size_t len) {
        // Auto generate
        SocketIO sio(serverinf);
        char buf[8192];
        FileInfo fi;

        // IMPORTANT trigger master execute serverAction 
        sio.socketWriter->sendFrame(TaskFlag::ls, len);
        sio.socketWriter->write(arg, len);
        sio.socketReader->readFrame();
        if (sio.socketReader->getFrameFlag() == TaskStat::failed) {
            sio.socketReader->read(buf, 8192);
            std::cout << buf << std::endl;
        } else {
            // 将socket描述符转为FILE文件流以按行读取
            FILE *fp = fdopen(serverinf.socket_fd, "r");
            unsigned long long total = sio.socketReader->getFrameLength();
            while ( total > 0 ) {
                fgets(buf, 8192, fp);
                total -= strlen(buf);
                fi.parse(buf, fi);
                std::cout << fi.toStandardStr();
            }
        }
        return AUTO_CLOSE;
    }
    int Ls::serverAction(socketinf clientinf, unsigned long long dataLength) {
        // Auto generate
        SocketIO sio(clientinf);
        sio.socketReader->resetPayloadLen(dataLength);
        char buf[8192] = {0};
        sio.socketReader->read(buf, dataLength);
        std::list<FileInfo> res;
        std::string send_buf;
        try {
            char path[8192];
            strcpy(path, configReader.getConfig(CONFIG_RESOURCE_DIR, CONFIG_RESOURCE_DIR_DEFAULT).c_str());
            strcat(path, "/");
            strcat(path, buf);
            res = FileUtils::scanDir(path);
        }
        catch(const Exception& e) {
            size_t len = strlen(e.what());
            sio.socketWriter->sendFrame(TaskStat::failed, len);
            sio.socketWriter->write(e.what(), len);
        }
        for (auto i = res.begin(); i != res.end(); i++) {
            send_buf.append(i->toString() + "\n");
        }
        
        sio.socketWriter->sendFrame(TaskStat::success, send_buf.length());
        sio.socketWriter->write(send_buf.c_str(), send_buf.length());
        return AUTO_CLOSE;
    }
}
